import time, logging
import re
import sys


NOT_IMPLEMENTED=1
BAD_FORMAT=2


logger = logging.getLogger("nebpublisher.parser")


class Parser():
  
  def __init__ (self, topics):
    self.load_types()
    self.topics = topics
    
    # compile the regexps once
    for key in list(self.topics.expressions):
      topic = topics.expressions[key]
      regexp = topic['regexp']
      topic['regexp'] = re.compile(regexp)
      topics.expressions[key] = topic
     
      
  """ This function loads the types and the functions responsible for
      parsing each message event
  """  
  def load_types(self):
    self.switch = {
      13: self.parse_service_check,
      14: self.parse_host_check,
    }

  def parse(self, type, message):
    try:
      return self.switch[type](message)
    except KeyError, e:
      self.not_implemented_type(type)
      return NOT_IMPLEMENTED
    except Exception, e:
      logger.warn('Unknown exception %s' % str(sys.exc_info()))
      exit(1)

  def not_implemented_type(self, type):
    logger.warn("Type %i has no parser." % type)
    return
  
  def not_implemented_service(self, service):
    logger.warn("Service %s has no parser." % service)
    return
 
  def parse_service_check(self, message):
    if message == None:
        return BAD_FORMAT

    logger.debug("Message %s - service check" % message)
    data = []
    data = message.split('^')
    if len(data) < 4:
        return BAD_FORMAT
    if len(data[0]) == 0 or len(data[1]) == 0  or len(data[2]) == 0 or len(data[3]) == 0:
        return BAD_FORMAT

    logger.debug("Host %s - description %s - state %s - output %s" %(data[0],data[1],data[2],data[3]))

    try:
      #Verifies the existance of this event type
      self.topics.expressions[data[1]]['eventtype']
    except KeyError:
      self.not_implemented_service(data[1])
      logger.warn("There is no such key for service_check: %s" % data[1])
      return NOT_IMPLEMENTED 
    
    topic = self.topics.expressions[data[1]]
    event = self.create_event_from_regexp(data[0], data[3], topic)              

    return event


  def parse_host_check(self, message):
    if message == None or len(message) == 0:
        return BAD_FORMAT

    logger.debug("Message %s - host check" % message)
    data = []
    data = message.split('^')

    if len(data) < 2:
        return BAD_FORMAT
    if len(data[0]) == 0 or len(data[1]) == 0:
        return BAD_FORMAT

    logger.debug("Host %s - output %s" % (data[0],data[1]))
        
    topic = self.topics.expressions['host']
    event = self.create_event_from_regexp(data[0], data[1], topic)
    return event
 
 
  def create_event_from_regexp(self, host, message, topic):
    event = {'host' : host}
    logger.debug('Message to be matched: %s \n Topic: %s' % (message, str(topic)))
    r = topic['regexp']
 
    m = r.match(message)

    if m == None:
        return BAD_FORMAT
    
    i = 1 # first match is the whole expression

    try:
      for property in topic['properties']:
        if m.group(i) != None:
          event[property] = m.group(i)
        i = i + 1
    except Exception:
      logger.warn("Regexp does not produce a valid information for %s" % topic['eventtype'])
      return NOT_IMPLEMENTED
      
    event['eventtype'] = topic['eventtype']
    logger.debug('event: %s' % str(event))
    return event
